<script>
	import Notice from '@/components/notice.vue';
	import {
		getTemplate
	} from "@/api/user.js";
	import {
		md5
	} from "js-md5";
	import {
		mapState
	} from "vuex";

	export default {
		globalData: {
			account: null
		},
		watch: {
			"$store.state.isLogin"(val) {
				if (val) {
					this.openWS();
					getTemplate().then(res => {
						uni.setStorageSync("copyTemplate", res.data);
					});
				} else {
					uni.closeSocket();
				}
			}
		},
		onLaunch: function(option) {
			console.log('App Launch')
			this.checknetwork();

			uni.getPushClientId({
				success: (res) => {
					let push_clientid = res.cid
					console.log("cid=", push_clientid);
				},
				fail: (err) => {
					console.log(err);
				}
			});

			if (!!option.query.openid) {
				return;
			}
			if (!!uni.getStorageSync("token")) {
				this.$store.state.isLogin = true;
			}

			const result = uni.getSystemInfoSync();
			// uni.setStorageSync("statusBarHeight", result.statusBarHeight);
			uni.setStorageSync("safeareaHeight", result.screenHeight - result.safeArea.bottom);
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			openWS() {
				const wssUrl = "wss://yqjc.cezhiyun.com/wss";
				uni.connectSocket({
					url: wssUrl + "?data=" + md5(uni.getStorageSync("token")),
				});
				uni.onSocketOpen(() => {
					console.log("WebSocket连接已打开！");
				});
				uni.onSocketError(() => {
					console.log("WebSocket连接打开失败，请检查！");
				});
				uni.onSocketMessage((res) => {
					let data = JSON.parse(res.data);
					if (data.title) {
						this.$store.state.noticeList = [data.title.trim().replace(/\n/g, "")];
						this.$store.state.noticeJson = data;
						clearInterval(this.$timer)
						let seconds = 20;
						this.$timer = setInterval(() => {
							seconds--;
							if (seconds == 0) {
								this.$store.state.noticeList = [];
								clearInterval(this.$timer);
							}
						}, 1000);
					}
				});
			},
			checknetwork() {
				uni.onNetworkStatusChange(function(res) {
					if (res.isConnected) {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					} else {
						uni.showModal({
							title: '系统提示',
							content: '当前设备无网络或网络较差',
							cancelText: '取消',
							confirmText: '确定',
							success: (res) => {
								if (res.confirm) {
									uni.reLaunch({
										url: '/pages/index/index'
									})
								} else {
									// #ifdef H5
									uni.reLaunch({
										url: '/pages/index/index'
									})
									// #endif
									// #ifdef APP-PLUS
									plus.runtime.quit()
									// #endif
								}
							}
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	@import "uview-ui/index.scss";

	page {
		height: 100%;
	}
</style>